import axios from 'axios'
import router from '@/router'
// import {message} from 'element-ui'
import Vue from 'vue'

let baseURL = 'http://127.0.0.1'
let config = {
  baseURL: baseURL,
  timeout: 3000
}
let _axios = axios.create(config)
_axios.interceptors.response.use(res => {
    // console.log(res);

    if (res.data.code === 401) {
      Toast('无权限操作')
    }
    if (res.data.code === 400) {
      // Toast("登录过期，请重新登录")
      // router.push({
      //   name: 'login',
      //   params: {
      //     isVerFalse: true
      //   }
      // }).then(r => {
      //   location.reload()
      //   console.log(r)
      // })
    }
    if (res.data.code === 300) {
      Vue.prototype.$message({
        message: res.data.msg,
        type: 'warning'
      })
    }
    if (res.data.code >= 500) {
      Vue.prototype.$message.error('服务器发生错误')
    }
    if (res.data.code === 404) {
      Toast('请求网络失败')
    }

    if (res.data.code === 200) {
      if (res.data.isAlert) {
        Vue.prototype.$message({
          type: 'success',
          message: res.data.msg
        })
      }
    }
    return res

  },
  err => {
    if (err) {
      //在这里关闭请求时的loading动画效果
      Vue.prototype.$message.error('服务器发生错误')
    }
    return Promise.reject(err)
  })

const http = {
  get (url = '', params = {}) {
    return new Promise((resolve, reject) => {
      _axios({
        url,
        params,
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'token': localStorage.getItem('token')
        },
        method: 'GET'
      }).then(res => {
        resolve(res)
        return res
      }).catch(error => {
        reject(error)
      })
    })
  },
  post (url = '', params = {}) {
    return new Promise((resolve, reject) => {
      _axios({
        url,
        data: params,
        // headers: {'Content-Type': ' application/x-www-form-urlencoded'},
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'token': localStorage.getItem('token')
        },
        method: 'POST'
      }).then(res => {
        resolve(res.data)
        return res
      }).catch(error => {
        reject(error)
      })
    })
  },

}

function Toast (msg) {
  console.log(msg)
}

export default http
